package com.cskaoyan.utils;


import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * 创建日期: 2022/03/22 10:06
 *
 * @author ciggar
 */
public class JDBCUtils {

    static String url;
    static String username;
    static String password;
    static String driverClassName;

    static {

        try {
            // 读取配置文件
            FileInputStream in = new FileInputStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(in);

            // 取值
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            driverClassName = properties.getProperty("driverClassName");

        }catch (Exception ex) {
            ex.printStackTrace();
        }


    }



               // 获取连接
        public static Connection getConnection(){

            Connection connection = null;

            try {

                // 1. 注册驱动
//                DriverManager.registerDriver(new Driver());
//                new Driver();
                Class.forName(driverClassName);


                // 2. 建立连接
                connection = DriverManager.getConnection(url, username, password);

        }catch (Exception ex) {
            ex.printStackTrace();
        }

        return connection;

    }


    // 释放资源
    public static void  close(ResultSet resultSet, Statement statement,Connection connection){

        try {
            // 6. 释放资源
            try {
                if(resultSet != null)  resultSet.close();
            } finally {
                try {
                    if(statement != null) statement.close();
                } finally {
                    if (connection != null) connection.close();
                }
            }

        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}
